import { Form } from "antd";
import type { FormItem } from "./Index";
import { useMemo } from "react";
import dayjs from "dayjs";
export const useProForm = ({ ...props }) => {
	const [form] = Form.useForm();
	const defaultSpan = 24;
	// 表单布局
	const layout = {
		labelCol: { span: 4 },
		wrapperCol: { span: 24 },
	};

	const formLayout = useMemo(() => {
		return props?.formLayout ?? layout;
	}, [props?.formLayout]);

	// 表单提交
	const onFinish = (values: any) => {
		console.log(values);
		const valuesArray = Object.entries(values).map(([key, value]) => ({ key, value }));
		// console.log(valuesArray);
		// 如果存在范围，则将转化key和value的值
		for (let key = 0; key < valuesArray.length; key++) {
			// 获取当前key的value
			const value = valuesArray?.[key]?.value;
			// 获取当前key的范围
			const rangeName = props?.formItems?.[key]?.rangeName;
			// 获取当前key的格式
			const format = props?.formItems?.[key]?.format;
			// 获取当前key的名称
			const name = props?.formItems?.[key]?.name ?? "";
			// 获取当前type
			const type = props?.formItems?.[key]?.type ?? "";

			//多个日期
			if (type === "date") {
				if (rangeName && value) {
					const keyValue = Array.isArray(value) ? value : [];
					values[rangeName[0]] = Array.isArray(keyValue) ? dayjs(keyValue?.[0]).format(format as string) : "";
					values[rangeName[1]] = Array.isArray(keyValue) ? dayjs(keyValue?.[1]).format(format as string) : "";

					delete values[name];
				}

				// 单个日期
				if (value && !rangeName) {
					values[name] = dayjs(value as any).format(format as string);
				}
			}
		}
		console.log(values);
		props?.onFinish?.(values);
	};

	// 过滤隐藏的表单项
	const formItemNew = useMemo<FormItem[]>(() => {
		const { formItems } = props;
		return formItems.filter((item: FormItem) => !item.hidden);
	}, [props.formItems]);

	// 表单初始值
	const initialValues = useMemo(() => {
		const { formItems } = props;
		return formItems.reduce((acc: Record<string, any>, item: FormItem) => {
			acc[item.name] = item.initialValue;
			return acc;
		}, {});
	}, [props.formItems]);

	// 重置表单
	const resetForm = () => {
		form.resetFields();
	};

	// 关闭模态框
	const closeModal = () => {
		props?.closeModal?.();
	};

	// 设置表单值
	const setFromFieldsValue = (values: Record<string, any>) => {
		console.log(values);
		form.setFieldsValue(values);
	};

	return {
		form,
		defaultSpan,
		onFinish,
		formItemNew,
		initialValues,
		formLayout,
		resetForm,
		setFromFieldsValue,
		closeModal,
	};
};
